#include "flightscheckwindow.h"
#include <QApplication>
#include <QDate>
#include <QFrame>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QList>
#include <QMessageBox>
#include <QPushButton>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QWidget>
#include "QDebug"
#include "interfacemanager.h"
#include "logwindow.h"
#include "models.h"
#include "paywindow.h"
#include "ticketframe.h"
#include "ui_flightscheckwindow.h"
#include "userordertestwindow.h"

bool adult=true;
bool eco_class=true;

FlightsCheckWindow::FlightsCheckWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::FlightsCheckWindow)
    , manager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);

    // 为 QLineEdit 添加 clicked 信号
    CustomControl::addClickSignal(ui->DepartEdit_2);
    CustomControl::addClickSignal(ui->ApartEdit_2);

    // 创建对话框实例
    cityDialog = new ChooseCityDialog(this);
    cityDialog->setWindowFlags(Qt::Popup); // 设置为 Popup 类型
    cityDialog->hide();
    //创建日期选择对话框
    dateDialog = new CalendarDialog(this);
    dateDialog->setWindowFlags(Qt::Popup); // 设置为 Popup 类型
    dateDialog->hide();

    dateDialog2 = new CalendarDialog(this);
    dateDialog2->setWindowFlags(Qt::Popup); // 设置为 Popup 类型
    dateDialog2->hide();

    // 连接信号到槽
    connect(ui->DepartEdit_2,
            &QLineEdit::customContextMenuRequested,
            this,
            &FlightsCheckWindow::handleLineEditClick1);
    connect(ui->ApartEdit_2,
            &QLineEdit::customContextMenuRequested,
            this,
            &FlightsCheckWindow::handleLineEditClick2);
    connect(dateDialog, &CalendarDialog::dateSelected, this, &FlightsCheckWindow::updateDateDisplay);
    connect(dateDialog2, &CalendarDialog::dateSelected, this, &FlightsCheckWindow::updateDateDisplay_return);

    // 安装全局事件过滤器
    qApp->installEventFilter(this);
    flightsBox = ui->flightsBox;
    flightsBox2 = ui->flightsBox_2;

    //页面更新

    updateDateDisplay(selectedDate.departdate);
    updateDateDisplay_return(selectedDate.apartdate);
    updateLocationDisplay(Flight::flightsList);
    //绘制航班机票信息
    startlayout(ticketFrame,flightsBox,one_way,adult,eco_class);
    //switchway(ticketFrame,flightsBox,one_way);
    //populateFlightGrid(flightsBox,Flight::flightsList);弃用的机票显示

    qDebug() << "index:" << InterfaceManager::instance()->log_index;
    ui->stackedWidget->setCurrentIndex(InterfaceManager::instance()->log_index);
}

int FlightsCheckWindow::book_orderid = 0;
void resetScrollArea1(QScrollArea *scrollArea)
{
    // 获取 scrollArea 中的当前控件
    QWidget *widget = scrollArea->widget();

    // 删除所有子控件
    if (widget) {
        // 清除子控件
        QLayout *layout = widget->layout();
        if (layout) {
            QLayoutItem *child;
            while ((child = layout->takeAt(0)) != nullptr) {
                // 删除子控件和布局项
                delete child->widget(); // 删除控件
                delete child;           // 删除布局项
            }
        }

        // 将 QScrollArea 的内容恢复到初始状态（例如：恢复一个空白或默认控件）
        // 这里可以根据实际需求恢复到一个特定的控件，比如一个空的 QWidget 或一个初始布局
        widget->setLayout(new QVBoxLayout); // 创建新的空布局
        scrollArea->setWidget(widget);      // 将空控件重新设置为 QScrollArea 的内容
    }
}

void FlightsCheckWindow::startlayout(TicketFrame *ticketFrame,QGroupBox *flightsBox,bool one_way,bool adult,bool eco_class){
    ui->OneWayradioButton_2->setChecked(one_way);
    ui->RoundWayradioButton_2->setChecked(!one_way);
    ui->adult->setChecked(adult);
    ui->children->setChecked(!adult);
    ui->enconomy->setChecked(eco_class);
    ui->first->setChecked(!eco_class);
    if(one_way){
        ui->returnBox->hide();
        flightsBox2->hide();
    }
    else{
        ui->returnBox->show();
        flightsBox2->show();
    }
    switchway(ticketFrame,flightsBox,flightsBox2,one_way);
}

void FlightsCheckWindow::printflightlist(TicketFrame *ticketFrame,QGroupBox *flightsBox,const QList<Flight> &flightsList)
{
    qDebug() << "开始显示航班信息";

    // 清空 flightsBox 的布局内容
    QLayout *layout = flightsBox->layout();
    if (layout) {
        QLayoutItem *child;
        while ((child = layout->takeAt(0)) != nullptr) {
            delete child->widget();
            delete child;
        }
    } else {
        layout = new QVBoxLayout(flightsBox);
    }

    // 检查数据是否为空
    if (flightsList.isEmpty()) {
        QLabel *noDataLabel = new QLabel("暂无航班信息。", flightsBox);
        noDataLabel->setStyleSheet("font-size: 16px; color: gray; text-align: center;");
        layout->addWidget(noDataLabel);
        return;
    }

    // 滚动区域
    QScrollArea *scrollArea = new QScrollArea(flightsBox);
    scrollArea->setWidgetResizable(true);

    QWidget *scrollWidget = new QWidget();
    QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);
    scrollLayout->setAlignment(Qt::AlignTop);

    for (const Flight &flight : flightsList) {
        QWidget *ticket = ticketFrame->createTicketWidget(flight,eco_class);
        if (ticket) {
            scrollLayout->addWidget(ticket);

            QPushButton *bookButton = ticket->findChild<QPushButton *>("bookButton");
            if (bookButton) {
                connect(bookButton, &QPushButton::clicked, this, [this, flight]() {
                    this->onBookButtonClicked(flight);
                });
            } else {
                qDebug() << "No bookButton found.";
            }
        }
    }

    scrollArea->setWidget(scrollWidget);
    layout->addWidget(scrollArea);
    flightsBox->setLayout(layout);
}


void FlightsCheckWindow::switchway(TicketFrame *ticketFrame, QGroupBox *flightsBox, QGroupBox *flightsBox2, bool one_way) {
    if (one_way) {
        flightsBox2->hide();
        printflightlist(ticketFrame, flightsBox, Flight::flightsList);
    } else {

        flightsBox2->show();
        // QGroupBox *flightsBox2 = new QGroupBox(this);
        // QHBoxLayout *infoLayout = new QHBoxLayout;
        // infoLayout->addWidget(flightsBox);
        // infoLayout->addWidget(flightsBox2);
        // ui->verticalLayout_3->addLayout(infoLayout);
        // ui->verticalLayout_3->setStretch(1,6);
        printflightlist(ticketFrame, flightsBox, Flight::flightsList);
        printflightlist(ticketFrame, flightsBox2, Flight::flightsList_return);
    }
}


void FlightsCheckWindow::onTriggerFunction()
{
    qDebug() << "Function in FlightCheck triggered!";
    //将firstwindow中选择的日期传进该页面
    qDebug() << "Depart date in FlightCheck: " << selectedDate.departdate;
    QString dateStr = selectedDate.departdate.toString("yyyy-MM-dd");
    QStringList weekDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
    // 获取星期数字（1-7），并通过数组索引转换为文字
    QString dayOfWeekName = weekDays.at(selectedDate.departdate.dayOfWeek() - 1);
    qDebug() << "Depart date in FlightCheck: " << dateStr;
    ui->Date_1->setText(dateStr); // 更新 QLabel
    ui->Date_2->setText(dateStr);
    ui->DateOfWeek_1->setText(dayOfWeekName);
    ui->DateOfWeek_2->setText(dayOfWeekName);
}

void FlightsCheckWindow::onBookButtonClicked(const Flight &flight)
{
    // 示例：弹出提示框显示订票信息
    if (LogWindow::userId != 0) {
        QMessageBox::information(this,
                                 "订票",
                                 QString("您选择了订票：\n%1\n从 %2 到 %3")
                                     .arg(flight.flightNumber)
                                     .arg(flight.departure)
                                     .arg(flight.destination));

        // 从控件读取数据
        QString ticket_type;
        QString seat_type;
        if (ui->adult->isChecked())
            ticket_type = "adult";
        if (ui->children->isChecked())
            ticket_type = "children";
        if (ui->enconomy->isChecked())
            seat_type = "Economy";
        if (ui->first->isChecked())
            seat_type = "First";

        // 创建一个 JSON 对象，封装请求体
        QJsonObject json;
        json["user_id"] = LogWindow::userId;
        json["seat_type"] = seat_type;
        json["ticket_type"] = ticket_type;
        json["flight_id"] = flight.id;
        json["order_count"] = ui->spinBox->value();

        qDebug() << "Preparing request data:" << json;

        // 将 JSON 对象转换为 JSON 文档
        QJsonDocument doc(json);
        QByteArray data = doc.toJson();

        // 设置请求头
        QNetworkRequest request(
            QUrl("http://127.0.0.1:8080/api/orders/create")); // 替换为你的 API URL
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        // 发送 POST 请求
        QNetworkReply *reply = manager->post(request, data);
        qDebug() << "发送请求";

        // 连接请求完成信号
        connect(reply,
                &QNetworkReply::finished,
                this,
                &FlightsCheckWindow::onOrdersCreateRequestFinished);
        qDebug() << "完成连接";

        InterfaceManager ::instance()->unregisterPage("/MainWindow/First/Pay");
        PayWindow *paywindow = new PayWindow();
        InterfaceManager::instance()->registerPage("/MainWindow/First/Pay", paywindow);
        InterfaceManager::instance()->switchToPage("/MainWindow/First/Pay");
    } else {
        QMessageBox::warning(this, "提示", QString("请先登陆"));
    }
}

void FlightsCheckWindow::onOrdersCreateRequestFinished()
{
    // 获取网络回复
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

    // 如果请求失败，输出错误信息
    if (reply->error() != QNetworkReply::NoError) {
        QString errorString = reply->errorString(); // 获取错误信息
        qDebug() << "Request failed with error:" << errorString;
        QMessageBox::critical(this, "Error", "Flight search request failed: " + errorString);
        reply->deleteLater();
        return;
    }

    // 请求成功，处理响应数据
    QByteArray response = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(response);
    QJsonObject jsonResponse = doc.object();

    // 处理响应
    int code = jsonResponse["code"].toInt();
    if (code == 200) {
        // 查询成功，获取航班数据
        QJsonObject orders = jsonResponse["data"].toObject();
        FlightsCheckWindow::book_orderid = orders["id"].toInt();
        qDebug() << "book id:" << FlightsCheckWindow::book_orderid;
    }
}

void FlightsCheckWindow::on_MoreDate_clicked()
{
    // 获取 QLineEdit 的左下角全局坐标
    QPoint globalPos = ui->MoreDate->mapToGlobal(QPoint(0, ui->MoreDate->height()));

    // 移动 QDialog 到 QPushButton 的正下方
    dateDialog->move(globalPos);
    dateDialog->show();
}
void FlightsCheckWindow::on_MoreDate_2_clicked()
{
    // 获取 QLineEdit 的左下角全局坐标
    QPoint globalPos = ui->MoreDate->mapToGlobal(QPoint(0, ui->MoreDate->height()));

    // 移动 QDialog 到 QPushButton 的正下方
    dateDialog2->move(globalPos);
    dateDialog2->show();
}

void FlightsCheckWindow::updateDateDisplay(const QDate &date)
{
    // 将选中的日期更新到 QLabel
    selectedDate.departdate = date;
    QString dateStr = date.toString("yyyy-MM-dd");
    QStringList weekDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
    // 获取星期数字（1-7），并通过数组索引转换为文字
    QString dayOfWeekName = weekDays.at(date.dayOfWeek() - 1);
    ui->Date_1->setText(dateStr); // 更新 QLabel
    ui->Date_2->setText(dateStr);
    ui->DateOfWeek_1->setText(dayOfWeekName);
    ui->DateOfWeek_2->setText(dayOfWeekName);
}

void FlightsCheckWindow::updateDateDisplay_return(const QDate &date)
{
    // 将选中的日期更新到 QLabel
    selectedDate.apartdate = date;
    QString dateStr = date.toString("yyyy-MM-dd");
    QStringList weekDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
    // 获取星期数字（1-7），并通过数组索引转换为文字
    QString dayOfWeekName = weekDays.at(date.dayOfWeek() - 1);
    ui->Date_3->setText(dateStr); // 更新 QLabel
    ui->DateOfWeek_3->setText(dayOfWeekName);
}
void FlightsCheckWindow::updateLocationDisplay(const QList<Flight>& flightsList){
    const Flight *headflight=&flightsList.constFirst();
    //将选中的地点更新
    ui->DepartEdit_2->setText(headflight->departure);
    ui->Depart_2->setText(headflight->departure);
    ui->ApartEdit_2->setText(headflight->destination);
    ui->Apart_2->setText(headflight->destination);

}

void FlightsCheckWindow::handleLineEditClick1()
{
    // 获取 QLineEdit 的左下角全局坐标
    QPoint globalPos = ui->DepartEdit_2->mapToGlobal(QPoint(0, ui->DepartEdit_2->height()));

    // 移动 QDialog 到 QLineEdit 的正下方
    cityDialog->move(globalPos);
    cityDialog->show();

    // 全选文字
    ui->DepartEdit_2->selectAll();

    // // 确保 QLineEdit 获得焦点以允许编辑文字
    // ui->DepartEdit_2->setFocus();

    // 确保 cityDialog 和 this 都有效
    if (cityDialog && this) {
        // 解除信号与槽的连接
        disconnect(cityDialog,
                   &ChooseCityDialog::citySelected,
                   this,
                   &FlightsCheckWindow::updateLineEditWithCity2);
    }
    connect(cityDialog,
            &ChooseCityDialog::citySelected,
            this,
            &FlightsCheckWindow::updateLineEditWithCity1);
}

void FlightsCheckWindow::handleLineEditClick2()
{
    // 获取 QLineEdit 的左下角全局坐标
    QPoint globalPos = ui->ApartEdit_2->mapToGlobal(QPoint(0, ui->ApartEdit_2->height()));

    // 移动 QDialog 到 QLineEdit 的正下方
    cityDialog->move(globalPos);
    cityDialog->show();

    // 全选文字
    ui->ApartEdit_2->selectAll();

    // // 确保 QLineEdit 获得焦点以允许编辑文字
    // ui->DepartEdit_2->setFocus();

    if (cityDialog && this) {
        // 解除信号与槽的连接
        disconnect(cityDialog,
                   &ChooseCityDialog::citySelected,
                   this,
                   &FlightsCheckWindow::updateLineEditWithCity1);
    }
    connect(cityDialog,
            &ChooseCityDialog::citySelected,
            this,
            &FlightsCheckWindow::updateLineEditWithCity2);
}

bool FlightsCheckWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->DepartEdit_2) {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

            // 确保删除键和其他键正常处理
            if (keyEvent->key() == Qt::Key_Backspace || keyEvent->key() == Qt::Key_Delete) {
                return false; // 将事件传递给 QLineEdit 的默认处理
            }
        }
    }

    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

        if (cityDialog && cityDialog->isVisible()) {
            // 检查鼠标点击是否在 cityDialog 或 QLineEdit 上
            bool clickedOutsideDialog = !cityDialog->geometry().contains(mouseEvent->globalPos());
            bool clickedOutsideLineEdit1 = !ui->DepartEdit_2->geometry().contains(
                ui->DepartEdit_2->mapFromGlobal(mouseEvent->globalPos()));
            bool clickedOutsideLineEdit2 = !ui->ApartEdit_2->geometry().contains(
                ui->ApartEdit_2->mapFromGlobal(mouseEvent->globalPos()));

            // 如果点击不在 dialog 或 lineEdit 上，则隐藏 dialog 并清除文字选中
            if (clickedOutsideDialog && clickedOutsideLineEdit1) {
                cityDialog->hide();

                // 清除 QLineEdit 的选中状态
                ui->DepartEdit_2->deselect();
            }
            if (clickedOutsideDialog && clickedOutsideLineEdit2) {
                cityDialog->hide();

                // 清除 QLineEdit 的选中状态
                ui->ApartEdit_2->deselect();
            }
        }
    }

    return QWidget::eventFilter(watched, event); // 保持默认处理
}

FlightsCheckWindow::~FlightsCheckWindow()
{
    delete ui;
}

void FlightsCheckWindow::on_DepartEdit_2_textEdited(const QString &arg1)

{
    cityDialog->hide();
}

void FlightsCheckWindow::updateLineEditWithCity1(const QString &cityName)
{
    // 更新 QLineEdit 的文本
    ui->DepartEdit_2->setText(cityName);
    ui->Depart_2->setText(cityName);
    cityDialog->hide();
}
void FlightsCheckWindow::updateLineEditWithCity2(const QString &cityName)
{
    // 更新 QLineEdit 的文本
    ui->ApartEdit_2->setText(cityName);
    ui->Apart_2->setText(cityName);
    cityDialog->hide();
}
//页面跳转
void FlightsCheckWindow::on_pushButton_clicked()
{
    InterfaceManager::instance()->switchToPage("/MainWindow/First/Enroll");
}

void FlightsCheckWindow::on_pushButton_2_clicked()
{
    InterfaceManager::instance()->switchToPage("/MainWindow/First/Log");
}

void FlightsCheckWindow::on_pushButton_3_clicked()
{
    InterfaceManager::instance()->unregisterPage("/MainWindow/First/Order");
    UserordertestWindow *orderwindow = new UserordertestWindow();
    InterfaceManager::instance()->registerPage("/MainWindow/First/Order", orderwindow);
    InterfaceManager::instance()->switchToPage("/MainWindow/First/Order");
}



void FlightsCheckWindow::on_OneWayradioButton_2_clicked()
{
    one_way=true;
    startlayout(ticketFrame,flightsBox,one_way,adult,eco_class);
}


void FlightsCheckWindow::on_RoundWayradioButton_2_clicked()
{
    one_way=false;
    startlayout(ticketFrame,flightsBox,one_way,adult,eco_class);
}


